package com.example.mapp.buildSql;

import com.example.entity.training.TrainingPlan;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

public class TrainingPlanMappSql {
    /**
     * 查询培训计划
     * @param trainingPlan
     * @return
     */
    public String queryTrainingPlan(TrainingPlan trainingPlan){
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT * FROM ");
        sb.append(" training_plan where 1=1 ");
        if(trainingPlan.getId() != null){
            sb.append(" and id = #{id}" );
        }
        if(StringUtils.isNotEmpty(trainingPlan.getPlanName())){
            String planName = "'%"+trainingPlan.getPlanName()+"%'";
            sb.append(" and plan_name like "+planName);
        }
        if(StringUtils.isNotEmpty(trainingPlan.getPlanContent())){
            String planContent = "'%"+trainingPlan.getPlanContent()+"%'";
            sb.append(" and plan_content like "+planContent);
        }
        if(StringUtils.isNotEmpty(trainingPlan.getLeadUnitId())){
            sb.append(" and lead_unit_id = #{leadUnitId}");
        }
        if(StringUtils.isNotEmpty(trainingPlan.getPlanType())){
            sb.append(" and plan_type = #{planType}");
        }
        if(StringUtils.isNotEmpty(trainingPlan.getStartDate())){
            sb.append(" and start_date >= #{startDate}");
        }
        if(StringUtils.isNotEmpty(trainingPlan.getEndDate())){
            sb.append(" and end_date <= #{endDate}");
        }
        sb.append(" order by id desc ");
        return sb.toString();
    }
    /**
     * 获取培训对象
     * @param trainingPlan
     * @return
     */
    public String queryUnitAndUser(TrainingPlan trainingPlan){
        String select = " DISTINCT p.id party_id,p.party_name,sur.user_id,su.user_name ";

        String table = " SUB_PARTY_INFO P  " + "LEFT JOIN PARTY_USER PU ON PU.PARTY_ID = P.ID   "
                + "LEFT JOIN SYS_USER_ROLE SUR ON PU.USER_ID = SUR.USER_ID "
                + "LEFT JOIN SYSTEM_ROLE SR ON SUR.role_id = SR.id  "
                + "LEFT JOIN sys_user su on su.id = sur.user_id ";

        String whereParam = " and SR.role_name like '%管理人员%' ";
        String planType = trainingPlan.getPlanType();
        if(planType != null && !"".equals(planType)){
            whereParam += " and P.PARTY_TYPE = #{planType}";
        }
        String leadUnitId = trainingPlan.getLeadUnitId();
        if(leadUnitId != null && !"".equals(leadUnitId)){
            whereParam += " and p.id != #{leadUnitId} ";
            whereParam += " and p.parent_id=#{leadUnitId} ";
        }
        String where = " 1=1 " + whereParam;
        String sql = new SQL() {
            {
                SELECT(select);
                FROM(table);
                WHERE(where);
            }
        }.toString();
        return sql;
    }
}
